#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <set>

using namespace std;

class Solution {
    public:
        string simplifyPath(string path) {
            stack<string> myStack;                            
            int lastPos = 0;
            for (int i = 1; i < path.size(); i++) {
                if (path[i] == '/') {
                    string str = path.substr(lastPos+1, i-lastPos-1);
                    lastPos = i;
                    if (str.size() == 0) continue;
                    //cout << str << endl;
                    if (str == "..") {if (!myStack.empty()) myStack.pop(); continue;}
                    if (str == ".") continue;
                    else myStack.push(str);
                }
            }
            if (lastPos != path.size()-1) {
                string str = path.substr(lastPos+1, path.size()-lastPos-1);
                if (str == "..") { if(!myStack.empty()) myStack.pop();}
                else if (str != "." && str.size() != 0) myStack.push(str);
            }
            string ans;
            while(!myStack.empty()){
                ans = myStack.top() + (ans.size() == 0 ? "" :"/") + ans;
                myStack.pop();
            }
            ans = "/" + ans;
            return ans;
        }
};

//add better code
string simplifyPath(string path) {
    stack<string> stk;
    for (int i = 0; i < path.size(); ) { 
        while(path[i] == '/' && i < path.size()) i++;
        string cur;
        while(path[i] != '/' && i < path.size()) { 
            cur += path[i];
            i++;
        }   
        if (cur == "..") {
            if (!stk.empty()) 
                stk.pop();
        } else if (cur == ".") {}
        else  if (cur.size() == 0){}
        else stk.push(cur);
        i++;
    }   
    string ans;
    if (stk.empty()) return "/";
    
    while(!stk.empty()) {
        ans = '/' + stk.top() + ans;
        stk.pop();
    }
    return ans;
}


//test on 1337 online judge and pass all the test
int main(int argc, char **argv)
{
    Solution mySolution;
    string result;
    
    cout << "-----------------Test 1--------------------" << endl;
    result = mySolution.simplifyPath("/../");
    cout << result << endl;


    cout << "-----------------Test 2--------------------" << endl;
    result = mySolution.simplifyPath("/..");
    cout << result << endl;


    cout << "-----------------Test 3--------------------" << endl;
    result = mySolution.simplifyPath("/.");
    cout << result << endl;


    cout << "-----------------Test 4--------------------" << endl;


    cout << "-----------------Test 5--------------------" << endl;



}
